package com.gopay.checkorder.service.task;

import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BankOrderType;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.CcbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.cmb.ebank.queryNtnstqry.CmbDownLoadMessage;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.StringTools;
import com.gopay.remote.bank.BcdlInteractRemoteService;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 招商银行对账明细下载
 * 2017/8/31
 * ssj
 */
public class CmbCheckDownloadTaskImpl implements Task {
    private final static Logger logger = LoggerFactory.getLogger(CmbCheckDownloadTaskImpl.class);
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "ipayDayEndConfig")
    private Map<String, String> ipayDayEndConfig;

    @Resource(name = "bankBcdlClient")
    private BcdlInteractRemoteService bankBcdlClient;

    private int COUNT_SIZE = 30; // 包内最大订单数

    private String bank;

    /**
     * 时间格式：yyyy-MM-dd' 'HH:mm:ss'.
     */
    public static String yyyy_MM_dd_HH_mm = "yyyyMMdd HH:mm";

    @Override
    public void doTask() {
        try {

            StopWatch sw = new StopWatch();
            sw.start();
            if ("off".equals(ipayDayEndConfig.get("mailSwitch"))) {
                logger.error("CmbCheckDownloadTaskImpl: 不进行操作直接返回!");
                return;
            }
            CmbDownLoadMessage msg = new CmbDownLoadMessage();
            //获取当前系统时间日期
            String DateStr1 = getCurrDate();
            String DateStr2 = GetDate() + " 03:30";
            String DateStr3 = GetDate() + " 10:30";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm");
            Date dateTime1 = dateFormat.parse(DateStr1);
            Date dateTime2 = dateFormat.parse(DateStr2);
            Date dateTime3 = dateFormat.parse(DateStr3);
            String startDate = "";
            int querySize_1 = getBcdlOrderCount(getSpecifiedDayBefore(GetDate())); // 昨日订单查询数
            logger.info("CmbCheckDownloadTaskImpl 昨日订单查询数  querySize_1="+querySize_1);
            int querySize_2 = getBcdlOrderCount(DateStr1.substring(0, 8)); // 今日订单查询数
            logger.info("CmbCheckDownloadTaskImpl 今日订单查询数  querySize_2="+querySize_2);
            //每天凌晨3点半执行一次,获取前一天的招商对账信息
            if (dateTime1.getTime() == dateTime2.getTime()) {
                // 前一天日期
                startDate = getSpecifiedDayBefore(GetDate());
                msg.setOrderDate(startDate);
                msg.setDateTypes("0330");
                msg.setQuerySize(querySize_1!=0?querySize_1:100);
                logger.info("CmbCheckDownloadTaskImpl 上午03:30 开始执行招商对账明细信息当,日期为:" + startDate);
            } else if (dateTime1.getTime() == dateTime3.getTime()) {//上午10:30 开始执行招商对账明细信息当
                //开始日期
                startDate = GetDate();
                msg.setOrderDate(startDate);
                msg.setDateTypes("1030");
                msg.setQuerySize(querySize_2!=0?querySize_2:100);
                logger.info("CmbCheckDownloadTaskImpl 上午10:30 开始执行招商对账明细信息当,日期为:" + startDate);

            } else {
                //开始日期  下午三点半开始执行一次
                startDate = GetDate();
                msg.setOrderDate(startDate);
                msg.setDateTypes("1530");
                msg.setQuerySize(querySize_2!=0?querySize_2:100);
                logger.info(" CmbCheckDownloadTaskImpl 上午15:30 开始执行招商对账明细信息当,日期为:" + startDate);

            }
            msg.setBank("CMB");
            msg.setHost(ipayDayEndConfig.get("sendmail.host"));
            msg.setSender(ipayDayEndConfig.get("sendmail.sender"));
            msg.setUsername(ipayDayEndConfig.get("sendmail.username"));
            msg.setPassword(ipayDayEndConfig.get("sendmail.password"));
            msg.setReceiver(ipayDayEndConfig.get("sendmail.receiver"));
            msg.setCc(ipayDayEndConfig.get("sendmail.cc"));

            logger.info("CmbCheckDownloadTaskImpl  招商银行对账明细收件人信息-----" + "host=" + ipayDayEndConfig.get("sendmail.host") +
                    ",sender=" + ipayDayEndConfig.get("sendmail.sender") + ",username=" + ipayDayEndConfig.get("sendmail.username") + ",receiver=" + ipayDayEndConfig.get("sendmail.receiver")
                    + ",cc=" + ipayDayEndConfig.get("sendmail.cc")+"传入的参数值："+msg);
            logger.info("开始执行招商对账明细job----------------------------");
            Result result = bankBcdlClient.queryAcctDetail(msg);
            if (ProcCodeConstants.PROC_CODE_100S1000.equals(result.getResultCode()) || CcbConstants.BCDL_RESULT_CODE_SUCC.equals(result.getResultCode())) {
                logger.info("招商对账查询明细成功---交易码:" + result.getResultCode() + result.getErrorMsg());
            } else if (ProcCodeConstants.PROC_CODE_100F1002.equals(result.getResultCode())) {
                logger.info("招商对账查询明细失败---交易码:" + result.getResultCode() + "错误原因:" + "内部系统异常超时");
            } else {
                logger.info("招商对账查询明细失败---交易码:" + result.getResultCode() + "错误原因:" + result.getErrorMsg());
            }
            logger.info("结束招商对账明细job----------------------------");

            sw.stop();
        } catch (Exception e) {
            logger.error("CmbCheckDownloadTaskImpl  异常");
            e.printStackTrace();
        }

    }


    /**
     * 获得指定日期的前一天
     *
     * @param specifiedDay
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayBefore(String specifiedDay) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyyMMdd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyyMMdd").format(c.getTime());
        return dayBefore;
    }

    /**
     * 返回系统当前日期
     *
     * @return
     */
    public static String GetDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
        return date;
    }

    public void setBank(String bank) {
        this.bank = bank;
    }

    public String getBank() {
        return bank;
    }

    /**
     * 获取当前时间
     *
     * @param pattern 格式
     * @return
     */
    public static String getCurrDate(String pattern) {
        long d = System.currentTimeMillis();
        Date date = new Date(d);

        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


    /**
     * 获取当前时间(格式:yyyyMMddHHmm)
     *
     * @return
     */
    public static String getCurrDate() {
        return getCurrDate(yyyy_MM_dd_HH_mm);
    }

    /**
     * 查询工行银企付款订单
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public int getBcdlOrderCount(String date) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date queryDate = formatter.parse(date); // 取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(queryDate);
        calendar.add(calendar.DATE, 1);
        queryDate = calendar.getTime();
        String endTime = formatter.format(queryDate);
        logger.error("CmbCheckDownloadTaskImpl getBcdlOrderCount beginTime: " + date + "endTime: " + endTime);

        StringBuffer sql = new StringBuffer(250);
        sql.append("select b.GOPAY_OUT_ORDER_ID,b.GOPAY_ORDER_ID from BIS_BANK_MAIN_ORDER b ");
        sql.append(" where b.BANK_BIZ_PROD_CODE = :bankBizProdCode ");
        sql.append(" and b.ORDER_TYPE = :orderType ");
        sql.append(" and b.GOPAY_BANK_CODE = :bankCode ");
        sql.append(" and b.SEND_BANK_TM >=to_date(:beginTime ,'yyyymmdd') ");
        sql.append(" and b.SEND_BANK_TM <to_date(:endTime ,'yyyymmdd') ");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("bankBizProdCode", BisBankBusinessProd._09.value);
        params.put("orderType", BankOrderType.GOPAY_BIS_ORDER);
        params.put("bankCode", BankConstants.BANK_LOGO_CMB);
        params.put("beginTime", date);
        params.put("endTime", endTime);
        List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), params);

        List<String> orderIds = new ArrayList<String>();
        for (Object[] bankOrderId : list) {
            orderIds.add(StringTools.checkNulltoString(bankOrderId[0]));
        }
        logger.error("CmbCheckDownloadTaskImpl  getBcdlOrderCount size: " + orderIds.size());
        int size = orderIds.size() / COUNT_SIZE + ((orderIds.size() % COUNT_SIZE == 0) ? 0 : 1);
        return size;
    }

}